package com.steven.ourcontest.contest.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.steven.ourcontest.base.BaseViewModel
import com.steven.ourcontest.contest.api.ContestApi
import com.steven.ourcontest.contest.bean.MatchInfoRes
import com.steven.ourcontest.team.api.TeamApi
import com.steven.ourcontest.utils.plusAssign
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.lang.Exception
import java.util.concurrent.TimeUnit
import kotlin.math.abs

class SearchMatchViewModel : BaseViewModel() {

    private val _matchResponse = MutableLiveData<com.steven.ourcontest.team.bean.MatchInfoRes>()
    val matchResponse: LiveData<com.steven.ourcontest.team.bean.MatchInfoRes>
        get() = _matchResponse

    @Volatile
    private var lastChangeTime = 0L
    private var lastQueryId = 0L
    fun editChange(str: String) {
        lastChangeTime = System.currentTimeMillis()
        disposed += Observable.timer(1, TimeUnit.SECONDS).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread()).subscribe({
                lastQueryId = 0L
                if (abs((System.currentTimeMillis() - lastChangeTime)) >= 800) {
                    queryMatch(str, lastQueryId)
                }
            }, {
            })
    }

    private fun queryMatch(matchName: String, lastId: Long) {
        disposed += TeamApi.instance.searchMatchList(matchName, lastId)
            .subscribe({
                _matchResponse.value = it
                lastQueryId = it.data.last().id
            }, {
                it.printStackTrace()
            })
    }

    fun queryMatchMore(matchName: String, success: () -> Unit) {
        disposed += TeamApi.instance.searchMatchList(matchName, lastQueryId)
            .subscribe({
                _matchResponse.value = it
                try {
                    success.invoke()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                lastQueryId = it.data.last().id
            }, {
                it.printStackTrace()
            })
    }
}